package com.gr

class PostController {

    def scaffold = true
	
	static navigation = [
		[group: 'tabs', action: 'personal', title: 'My Posts', order: 0],
		[action:'timeline', title: 'My Timeline', order: 1],
		[action: 'global', title: 'Everyone', order: 2],

	]
	
	def postService
		
	def timeline = {
		def user = User.findByUserId(params.id)
		
		def posts = Post.list(params)
		def postCount = Post.count()
		[ posts : postCount ]
		
		[ user : user ]
	}
	
	def addPost = {
	
		try {
			def newPost = postService.createPost(params.id, params.content)
			flash.message = "Added new Post: ${newPost.content}"	
		} catch (PostException pe) {
			flash.message = pe.message
		}
		redirect(action: 'timeline', id: params.id)
        
    }
	
	def addPostAjax = {
		try {
			def userToFind = new User(userId: 'Dima')
			def u1 = User.find(userToFind)
			def newPost = postService.createPost(u1.userId, params.content)
			def recentPosts = Post.findAllByUser(u1, [sort: 'dateCreated', order: 'desc', max: 20])
			render(template:"postentries", collection: recentPosts, var: 'post')
		} catch (PostException pe) {
			render {
				div(class:"errors", pe.message)
			}
		}

	}
}
